package com.hsj.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author:Teacher黄
 * @date:Created at 2018/11/13
 */
public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        Configuration configure = new Configuration().configure();
        // 在4.x版中创建sessionfactory时，需要传入一个参数serviceRegistry
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configure.getProperties()).build();
        sessionFactory = configure.buildSessionFactory(serviceRegistry);
    }

    /**
     * 获取sessionFactory;
     * @return
     */
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }

    /**
     * 获取session
     * @return
     */
    public static Session getSession(){
        return sessionFactory.openSession();
    }

    /**
     * 获取与当前线程绑定的session
     * @return
     */
    public static Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }


}
